package com.gjy.concurrency.clazz;

import org.junit.jupiter.api.Test;

import java.util.concurrent.Semaphore;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-05-18 11:26:59
 */
public class SemaphoreTest {

    @Test
    public void test1() {
        Semaphore sem = new Semaphore(2);
        Thread t1 = new Thread(new MyThread(sem, "Thread 1"));
        Thread t2 = new Thread(new MyThread(sem, "Thread 2"));

        t1.start();
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Finished.");
    }

    private static final class MyThread implements Runnable {
        private final Semaphore sem;
        private final String threadName;

        public MyThread(Semaphore sem, String threadName) {
            this.sem = sem;
            this.threadName = threadName;
        }

        public void run() {
            System.out.println(threadName + " is waiting for a permit.");

            try {
                sem.acquire();
                System.out.println(threadName + " gets a permit.");

                for (int i = 0; i < 5; i++) {
                    System.out.println(threadName + ": " + i);
                    Thread.sleep(1000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                sem.release();
            }

            System.out.println(threadName + " releases the permit.");
        }
    }

}
